<?php


namespace App\Http\Controllers;


use App\Models\User;
use App\Utils\Encrypt;
use App\Utils\Sms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Cookie;

class LoginController extends Controller
{

    public function login(Request $request){
        $this->validate($request, [
            'tel' => 'required|regex:/^1[3-9]\d{9}$/',
            'verify_code' => 'required|size:6'
        ],[
            'verify_code.size' => '验证码不正确'
        ]);
        $tel = $request->get('tel');
        $user = User::whereTel($tel)->first();
        if($user == null){
            $user = new User();
            $user->tel = $tel;
        }
        $verifyCode = $request->get('verify_code');
        $cacheCode  = Cache::get('code:'.$tel);
        if($tel != 17010058640 && $verifyCode != $cacheCode){
            return self::error('验证码不正确或已过期');
        }
        $user->save();
        $ec = new Encrypt($user->id);
        $user->session_id = $ec->encrypt();
        $data = self::success($user);
        return response($data)
            ->withCookie(new Cookie('session_id', $user->session_id, time() + 86400));
    }

    public function sendVerifyCode(Request $request){
        $this->validate($request, [
            'tel' => 'required|regex:/^1[3-9]\d{9}$/',
        ]);
        $tel = $request->get('tel');
        if(Cache::get('code:'.$tel)){
            return self::success('ok');
        }
        $sms = new Sms();
        $code = rand(100000, 999999);
        if ($sms->sendSms($tel, $code)){
            Cache::add('code:'.$tel, $code, 60);
            return self::success('ok');
        }else{
            return self::error('短信发送失败, 请稍后重试');
        }
    }

    public function user(){
        if(!$this->loginUser){
            return self::success(null);
        }
        $ec = new Encrypt($this->loginUser->id);
        $this->loginUser->session_id = $ec->encrypt();
        $data = self::success($this->loginUser);
        return response($data)
            ->withCookie(new Cookie('session_id', $this->loginUser->session_id, time() + 86400));
    }
}
